/*
*	Developed by Leonardo Chatain and Pedro Dusso, at Universidade Federal do Rio Grande do Sul, Brasil, 2009/1
*	Source available at glpacman.codeplex.com
*/

#include "Vector2D.h"

Vector2D::Vector2D(void):
	x(0), y(0)
{
}

Vector2D::Vector2D(float X, float Y) {
	x = X;
	y = Y;
}

Vector2D::Vector2D(Point2D p1, Point2D p2) {
	x = p2.getX() - p1.getX();
	y = p2.getY() - p1.getY();
}

Vector2D::~Vector2D(void)
{
}

float Vector2D::dotProduct(Vector2D other) {
	return x * other.getX() + y * other.getY();
}

Vector2D Vector2D::multiply(float c) {
	x *= c;
	y *= c;          
	return *this;
} 

float Vector2D::getNorm() {
	return sqrt(x * x + y * y);
}

void Vector2D::normalize() {
	if (!(x == 0 && y == 0)) {
		float norm = getNorm();
		x = x / norm;
		y = y / norm;
	}
}

float Vector2D::getAngleTo(Vector2D other) {
	if (x == 0 && y == 0)
		return 0;

	Vector2D unitary(1, 0);
	double thetaThis = toDegrees(acos(this->dotProduct(unitary)));
	if (y < 0)
		thetaThis = 360 -thetaThis;
	double thetaOther = toDegrees(acos(other.dotProduct(unitary)));
	if (other.getY() < 0)
		thetaOther = 360 -thetaOther;

	if (thetaOther >= thetaThis)
		return thetaOther - thetaThis;
	else
		return 360 - (thetaThis - thetaOther);
}

/*
A funcao multiplica um vetor por uma matriz de rotacao (sentido anti) dada por [ cos(theta)   -sin(theta) ]
                                                                               [ sin(theta)    cos(tehta) ]
Multiplicando a matriz pelo vetor temos:
      x' = x cos(theta) - y sen(theta)
      y' = x sen(theta) + y cos(theta)
*/
Vector2D Vector2D::rotate(float theta)
{
        //Rotaciona o vetor para a esquerda (sentido AH):
        float anguloRadianos = theta * PI / 180.0;
        float cosTheta = cos(anguloRadianos);
        float sinTheta = sin(anguloRadianos);

        float coordX = x*cosTheta - y*sinTheta;
        float coordY = x*sinTheta + y*cosTheta;

        x = coordX;
        y = coordY;
		return *this;
}

double Vector2D::toDegrees(double angulo)
{
        return angulo * 180 / PI;
}

double Vector2D::toRad(double angulo)
{
        return angulo * PI / 180;
}
